const express=require('express');
const mysql=require('mysql');
const urlobj=require('url');

const multer=require('multer');
//设置上传路径
var multerObj=multer({dest:'./www/img'});
const fs=require('fs');
const pathLib=require('path');

//引用自定义
const commte=require('../../../libs/common.js');
//链接数据库
var db=mysql.createPool({
    host:'localhost',
    user:'root',
    password:'',
    database:'leasedb'
});
//业务逻辑
module.exports = function() {
    var router = express.Router();


    router.use('/AddBillboard',function(req,res,next){
        //判断是否登陆
        if(req.session['userId']==null||req.session['userId']=="")
        {
            res.status(400).send('<script>alert("请登录");window.location.href="login.html";</script>').end();
        }
        //console.log(req.body);
       // console.log("原名文件"+req.files[0].originalname);
        //获得文件扩展名
        //console.log("文件后缀"+pathLib.parse(req.files[0].originalname).ext);
        //文件全名
        var ext=pathLib.parse(req.files[0].originalname).ext;
        //console.log("dxcvbnm"+ext);
        //文件旧存放路径
        var oldPath=req.files[0].path;
        // console.log("文件旧存放路径"+oldPath)
        //文件新存放路径
        var newPath=req.files[0].path+ext;
        //console.log("文件新存放路径"+newPath)
        //文件新名
        var newFileName=req.files[0].filename+ext;

        console.log("我的img"+req.body.activitSetTop);

        fs.rename(oldPath,newPath,function(err){
            if(err)
            {
                res.status(500).send('upload is error');
            }
            else
            {
                db.query("INSERT INTO `noticeinfo`(`Noticeid`, `NoticeTitle`, `adminId`, `Noticecontent`, `Noticepic`, `activitSetTop`, `Noticedata`) VALUES (0,'"+req.body.NoticeTitle+"',"+ +req.session['userId']+",'"+req.body.editorValue+"','"+newFileName+"',"+ +req.body.activitSetTop+",'"+ commte.getTime()+"')",function (err,data) {
                    if(err)
                    {
                        res.status(400).send('<script>alert("公告失败了!");</script>').end();
                    }else
                    {
                        res.status(400).send('<script>alert("添加成功");window.location.href="Billboard.html";</script>').end();
                        next();
                    }
                })

            }
        });


    });



    router.get('/AddBillboard.html',function(req,res,next){
        // console.log("sdafasdfasdfasdfa"+req.oneortwo);
        res.render("admin/AddBillboard.ejs",{secondwto:req.oneortwo});

    });
    return router;
}